
<?php
   require_once 'error_config.php' ;
   require_once 'mysql_result.php' ;

   class CMySql
   {
	  private $m_mysql ;

	  function __construct( $host, $user, $pwd, $db, $port =3306 )
	  {
		 $this->m_mysql =mysqli_init() ;
		 if( !$this->m_mysql )
		 {
			die( 'mysql init faild.' ) ;
		 }

		 if( !$this->m_mysql->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5) )
		 {
			die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
		 }

		 if( !$this->m_mysql->real_connect( $host, $user, $pwd, $db, $port ) )
		 {
			die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
		 }

		 /* change character set to utf8 */
		 if( !$this->m_mysql->set_charset("utf8") )
		 {
			die( 'Error loading character set utf8: '.$this->m_mysql->error);
		 }
	  }

	  function __destruct()
	  {
		 $this->Close() ;
	  }

	  function Escape( $var )
	  {
		 return $this->m_mysql->escape_string( $var ) ;
	  }

	  // Ues example:
	  //
	  // format:
	  // string    s
	  // integer   d, u, c, o, x, X, b
	  // double    g, G, e, E, f, F
	  //
	  function Format( $format, $params )
	  {
		 $params =array_map( array( $this, 'Escape' ), $params ) ;
		 $sql    =call_user_func_array( 'sprintf', array_merge( array( $format ), $params ) ) ;
		 //echo 'sql is: '.$sql.'<br/>' ;
		 return $sql ;
	  }

	  // Ues example:
	  //
	  // $format ='SELECT * FROM web_pay_records WHERE record_id =%d AND palyer_name LIKE %s LIMIT 1 ;' ;
	  // $params =array( 3, 'mygod' ) ;
	  // Select( $format, $params ) ;
	  //
	  // Result sql is:SELECT * FROM web_pay_records WHERE record_id =3 AND palyer_name LIKE mygod LIMIT 1 ;  
	  //
	  function Query( $format, $params )
	  {
		 $sql =$this->Format( $format, $params ) ;

		 $qR =$this->m_mysql->query( $sql, MYSQLI_STORE_RESULT ) ; //MYSQLI_USE_RESULT
		 if( $qR === false )
		 {
			$this->ShowError() ;
			return false ;
		 }

		 return new CSqlResult( $qR ) ;
	  }

	  // Ues example:
	  //
	  // 数据库格式：自增id，5个int， 15个string
	  //
	  // $record = array_merge( array( 0, 1,1,1,1,1 ), array_fill( 1, 15, 'oxx' ) ) ;
	  // var_export( $record ) ;
	  // echo '<br/>' ;
	  // $sqlConn->Replace( 'pvp_rank', $record ) ; 
	  //
	  // 注意，如果前面的是自增列，且输入为0, 那么默认是新增一条记录
	  function Replace( $tableName, $params )
	  {
		 $params =array_map( array( $this, 'Escape' ), $params ) ;

		 $sql ='REPLACE '.$tableName.' VALUES( ' ;

		 foreach( $params as $value )
		 {
			$sql .= '"' ;
			$sql .= $value ;
			$sql .= '"' ;
			$sql .= ',' ;
		 }

		 $sql = substr_replace( $sql, ' );', -1, 1 ) ;

		 //echo 'sql is: '.$sql.'<br/>' ;

		 $qR  =$this->m_mysql->query( $sql ) ;
		 if( $qR === false )
		 {
			$this->ShowError() ;
		 }

		 return $qR ;
	  }

		 
	  function ShowError()
	  {
		 echo $this->m_mysql->error.'<br/>' ;
	  }

	  private function Close()
	  {
		 $this->m_mysql && $this->m_mysql->close() ;
	  }

   }
?>

